#!/usr/bin/env python
# -*- coding: utf-8 -*-


from modules.user.user_mgr import UserMgr
from modules.project.project_mgr import ProjectMgr
from modules.task.task_mgr import TaskMgr
from modules.device.device_mgr import DeviceMgr
from modules.report.report_mgr import ReportMgr
from modules.template.template_mgr import TemplateMgr
from modules.config.config_mgr import ConfigMgr
import hashlib


class Control:
    def __init__(self, app, session):
        self.app = app
        self.session = session
        self.user_mgr = UserMgr(app, session)
        self.project_mgr = ProjectMgr(app, session)
        self.task_mgr = TaskMgr(app, session)
        self.device_mgr = DeviceMgr(app, session)
        self.report_mgr = ReportMgr(app, session)
        self.template_mgr = TemplateMgr(app, session)
        self.config_mgr = ConfigMgr(app, session)


    def destroy(self):
        if self.config_mgr:
            self.config_mgr.destroy()
            self.config_mgr = None
        if self.template_mgr:
            self.template_mgr.destroy()
            self.template_mgr = None
        if self.report_mgr:
            self.report_mgr.destroy()
            self.report_mgr = None
        if self.device_mgr:
            self.device_mgr.destroy()
            self.device_mgr = None
        if self.task_mgr:
            self.task_mgr.destroy()
            self.task_mgr = None
        if self.project_mgr:
            self.project_mgr.destroy()
            self.project_mgr = None
        if self.user_mgr:
            self.user_mgr.destroy()
            self.user_mgr = None
        self.session = None
        self.app = None 


    def __del__(self):
        self.destroy()


    def socketio_connect(self, request):
        self.app.logger.warning(f'{self.__class__}: method socketio_connect() is empty')

    
    def socketio_disconnect(self, request):
        self.app.logger.warning(f'{self.__class__}: method socketio_disconnect() is empty')


    def login(self, username: str, password: str, remember = False):
        user = None
        if username in self.user_mgr.users and self.user_mgr.users[username]['password'] == hashlib.md5(password.encode()).hexdigest():
            user = self.user_mgr.users[username]
        if user:
            # 登录成功，设置会话
            self.session['username'] = username
            self.session['name'] = user['name']
            self.session['role'] = user['role']
            # 如果选择了"记住我"，设置会话过期时间为30天
            if remember:
                self.session.permanent = True
                self.app.permanent_session_lifetime = timedelta(days=30)
            return True
        return False


    def logout(self):
        self.session.clear()
        return True